<template>
  <div>
    <div>
      <!-- show-checkbox  展示复选框
           check-strictly 取消父子关联（用户可能只有页面权限，没有按钮权限）
           采用key方式来获取节点，必须添加 node-key
       -->
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissionList"
        style="min-height:300px"
        :props="{ label: 'name' }"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="setRolesBtn"
        >确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleInfoAPI, assignPremAPI } from '@/api/setting'
import { listToTreeData } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      permissionList: [],
      loading: false // 加载效果
    }
  },
  created() {
    this.getPermissionListFn()
    this.getRoleInfoFn()
  },
  methods: {
    // 获取当前角色权限
    async getRoleInfoFn() {
      const res = await getRoleInfoAPI(this.roleId)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 获取权限列表
    async getPermissionListFn() {
      this.loading = true
      const res = await getPermissionList()
      this.permissionList = listToTreeData(res.data)
      this.loading = false
    },
    // 取消分配权限
    cancelButton() {
      this.$emit('closeEvent')
    },
    // 分配权限
    async setRolesBtn() {
      // 获取用户选中所有的树节点
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPremAPI({ id: this.roleId, permIds })
      this.$message.success(res.message)
      this.$emit('closeEvent')
    }
  }
}
</script>

<style>
</style>
